/**
 * 处理器函数
 * @param {*} state 可以存储任意的内容
 * @param {*} action 动作对象，也是普通的js对象，必须有个type属性，用来表示你要干什么
 */
let reducer = (state = 0, action) => {
  switch (action.type) {
    case "ADD":
      return state + 1;
    case "Minus":
      return state - 1;
  }
};

// 一个闭包
function createStore(reducer) {
  let state; // 可以存放任意内容
  let listeners = [];
  function getState() {
    // 用于获取当前的状态
    return state;
  }
  function dispatch(action) {
    // 派发
    state = reducer(state, action);
    listeners.forEach((l) => l()); // 状态改变的时候执行 发布
  }

  // 默认回派发一次
  dispatch({ type: "@@REDUX/INIT" });

  // 状态改变需要渲染页面
  // 订阅监听事件
  function subscribe(listener) {
    listeners.push(listener);
  }
  return {
    getState,
    dispatch,
    subscribe,
  };
}

//原始调用
store.dispatch({ type: "ADD" });

// 改造后
function add() {
  return { type: "ADD" };
}

function Minus() {
  return { type: "ADD" };
}
const actions = { add, Minus };
const boundActions = bindActionCreators(actions, store.dispatch);
boundActions.add;
boundActions.Minus;

/**
 * 传入老的actionCreators，返回一个新的函数
 * @param {*} actions
 * @param {*} dispatch
 */
function bindActionCreator(action, dispatch) {
  return function (...args) {
    return dispatch(action.apply(this, args));
  };
}
/**
 *
 * @param {*} action action创建者对象
 * @param {*} dispatch 派发动作的方法
 */
function bindActionCreators(actions, dispatch) {
  const boundActionCreators = {};
  if (typeof actions === "function") {
    return actions(dispatch);
  }
  for (const key in actions) {
    const actionCreator = actions[key];
    if (typeof actionCreators === "function") {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
    }

    dispatch;
  }
  return boundActionCreators;
}
